﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlyweightPattern
{
    /// <summary>
    /// 享元工厂
    /// </summary>
    public class FlyweightFactory
    {
        private static Dictionary<WordType, BaseWord> _WordDictionary = new Dictionary<WordType, BaseWord>();
        private static object GetWord_Lock = new object();

        public static BaseWord GetWord(WordType wordType)
        {
            BaseWord word = null;
            //lock (GetWord_Lock)
            //{
            if (_WordDictionary.ContainsKey(wordType))
            {
                word = _WordDictionary[wordType];
            }
            else
            {
                lock (GetWord_Lock)
                {
                    if (_WordDictionary.ContainsKey(wordType))
                    {
                        word = _WordDictionary[wordType];
                    }
                    else
                    {
                        switch (wordType)
                        {
                            case WordType.E:
                                word = new E();
                                break;
                            case WordType.L:
                                word = new L();
                                break;
                            case WordType.V:
                                word = new V();
                                break;
                            case WordType.N:
                                word = new N();
                                break;
                            default:
                                throw new Exception("wrong wordType");
                        }
                        _WordDictionary[wordType] = word;
                    }
                }
            }
            //}
            return word;
        }
    }
    public enum WordType
    {
        E,
        L,
        V,
        N,
        X1,
        X2
    }
}
